package cn.netty.exemple6;

import cn.netty.exemple6.marshall.MarshallCodeFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class SubReqClient {

    private NioEventLoopGroup requestGroup;
    private Bootstrap bootstrap;

    public void init(){
       requestGroup = new NioEventLoopGroup();
       bootstrap = new Bootstrap();
       bootstrap.group(requestGroup);
       bootstrap.channel(NioSocketChannel.class)
               .handler(new LoggingHandler(LogLevel.INFO))
               .option(ChannelOption.TCP_NODELAY,true);
    }

    public SubReqClient(){
        init();
    }

    public ChannelFuture doRequest(String host,int port) throws InterruptedException {

        this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {

            protected void initChannel(SocketChannel ch) throws Exception {

                ch.pipeline().addLast(MarshallCodeFactory.deCoder());
                ch.pipeline().addLast(MarshallCodeFactory.enCoder());
                ch.pipeline().addLast(new SubReqClientHandle());
            }
        });


        return  this.bootstrap.connect(host,port).sync();
    }

    public void release(){
        this.requestGroup.shutdownGracefully();
    }

    public static void main(String[] args) {
        SubReqClient client = new SubReqClient();
        ChannelFuture future = null;

        try {
            future = client.doRequest("127.0.0.1",8881);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }finally {
            client.release();
        }
    }
}
